package com.dxy.authresource.core;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.util.Arrays;
import java.util.Map;

/**
 * Created by cxf_dxy on 2018/10/26.
 */

@ConfigurationProperties(prefix = "auth.mapping")
@ConditionalOnClass({SpringApplicationContext.class,LoadResource.class})
public class AuthResourceClient {

    private static final Logger logger = LoggerFactory.getLogger(AuthResourceClient.class);

    String url;

    boolean master = false;

    private static final String APPLICATION_NAME_KEY="spring.application.name";


    @Autowired
    RestTemplate restTemplate;

    @Autowired
    LoadResource requestMapping;

    @PostConstruct
    public void execute(){
        try {
            if (!StringUtils.isEmpty(url) && !master) {
                logger.info("pushing auth resource for ->" + url);
                Map<String, Object> result = requestMapping.extractMethodMappings();
                result.put(APPLICATION_NAME_KEY, SpringApplicationContext.getApplicationName());
                String json = JSONObject.toJSONString(result, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullStringAsEmpty);
                Arrays.stream(url.split(",")).forEach(u -> {
                    try {
                        postForJson(u, json, String.class);
                        logger.info("push auth resource success to ->" + u);
                        return;
                    } catch (Exception e) {
                        logger.info("push auth resource error for ->" + u, e);
                    }
                });
            }
        }catch (Exception e){
            logger.info("push auth resource error for ->" + url, e);
        }

    }

    public <T> T postForJson(String url, String json, Class<T> responseType) throws RestClientException {
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        HttpEntity<String> entity = new HttpEntity<>(json,headers);
        return restTemplate.postForObject(url, entity,responseType);
    }

    public String getUrl() {
        return url;
    }


    public void setUrl(String url) {
        this.url = url;
    }

    public boolean getMaster() {
        return master;
    }

    public void setMaster(boolean master) {
        this.master = master;
    }
}
